import { BatchCheckDeviceNamesRequest, BatchRegisterDeviceWithApplyIdRequest, PubRequest, QueryDeviceInfoRequest, QueryProductListRequest, RegisterDeviceRequest } from '@alicloud/iot20180120';
import { AlicloudService } from '@app/alicloud';
import { ConfigureService } from '@app/configure';
import { Injectable } from '@nestjs/common';
import { createHash } from 'node:crypto'

@Injectable()
export class AliIotService {
  private aliToDeviceTopicReg:string;
  constructor(
    private readonly alicloud:AlicloudService,
    private readonly config:ConfigureService
  ){
    this.aliToDeviceTopicReg = config.get('aliToDeviceTopicReg')
  }

  pubToDevice(deviceId:number|string, product:string, msg:{[key:string]:any}) {
    const deviceName = String(deviceId).padStart(15, '0')
    msg.id = deviceName
    if(!msg.msgId) {
      msg.msgId = createHash('md5').update(Date.now() + deviceName).digest('hex').toLowerCase()
    }

    let req = new PubRequest({
        productKey : product,
        deviceName : deviceName,
        topicFullName : this.aliToDeviceTopicReg.replace(/\?/, product).replace(/\?/, deviceName),
        messageContent : Buffer.from(JSON.stringify(msg)).toString('base64')
    })

    return this.alicloud.createIotClient().pub(req)
  }

  pub(req:PubRequest) {
    return this.alicloud.createIotClient().pub(req)
  }

  async queryDeviceInfo(productKey:string, deviceId:number) {
    const req = new QueryDeviceInfoRequest({
      productKey,
      deviceName : String(deviceId).padStart(15, '0')
    })
    return this.alicloud.createIotClient().queryDeviceInfo(req)
}

  async registerDevice(productKey:string, deviceId:number) {
    const req = new RegisterDeviceRequest({
      productKey,
      deviceName : String(deviceId).padStart(15, '0')
    })
    return this.alicloud.createIotClient().registerDevice(req)
  }

  //查询产品
  async queryProductList() {
    const request = new QueryProductListRequest({
      pageSize: 20,
      currentPage: 1,
    })

    const res = await this.alicloud.createIotClient().queryProductList(request)
    return res.body.toMap().Data.List.ProductInfo
  }

  //检查设备
  async batchCheckDeviceNames(productKey:string, deviceIds:number[]) {
    const req = new BatchCheckDeviceNamesRequest({
      productKey : productKey,
      deviceName : deviceIds.map(id => String(id))
    })
    const res = await this.alicloud.createIotClient().batchCheckDeviceNames(req)
    const r = res.body.toMap()
    return r.Success ? r.Data.ApplyId : null
  }

  //注册设备
  async batchRegisterDeviceWithApplyId(productKey:string, applyId:string) {
    const req = new BatchRegisterDeviceWithApplyIdRequest({
      productKey : productKey,
      applyId : applyId
    })
    const res = await this.alicloud.createIotClient().batchRegisterDeviceWithApplyId(req)
  }
}
